package com.ty.cloudpicture.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ty.cloudpicture.annotation.AuthCheck;
import com.ty.cloudpicture.common.*;
import com.ty.cloudpicture.exception.BusinessException;
import com.ty.cloudpicture.exception.ThrowUtils;
import com.ty.cloudpicture.manager.auth.SpaceUserAuthManager;
import com.ty.cloudpicture.model.dto.space.SpaceAddRequest;
import com.ty.cloudpicture.model.dto.space.SpaceLevel;
import com.ty.cloudpicture.model.dto.space.SpaceQueryRequest;
import com.ty.cloudpicture.model.dto.space.SpaceUpdateRequest;
import com.ty.cloudpicture.model.entity.Space;
import com.ty.cloudpicture.model.entity.User;
import com.ty.cloudpicture.model.enums.SpaceLevelEnum;
import com.ty.cloudpicture.model.vo.SpaceVO;
import com.ty.cloudpicture.service.SpaceService;
import com.ty.cloudpicture.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/space")
@Api(tags = "空间管理")
@AllArgsConstructor
public class SpaceController {
    private final SpaceService spaceService;
    private final UserService userService;
    private final SpaceUserAuthManager spaceUserAuthManager;

    @PostMapping("/add")
    @ApiOperation(value = "添加空间")
    public BaseResponse<Long> addSpace(@RequestBody SpaceAddRequest spaceAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(spaceAddRequest == null, ErrorCode.PARAMS_ERROR);
        log.info("addSpace:{}", spaceAddRequest);
        long spaceId = spaceService.createSpace(spaceAddRequest, userService.getLoginUser(request));
        return ResultUtils.success(spaceId);
    }
    @PostMapping("/delete")
    @ApiOperation(value = "删除空间")
    public BaseResponse<Boolean> deleteSpace(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <=0, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        Space oldSpace = spaceService.getById(id);
        if (oldSpace == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        if (!oldSpace.getUserId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean delete = spaceService.removeById(id);
        return ResultUtils.success(delete);
    }
    @PostMapping("/update")
    @ApiOperation(value = "更新空间")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateSpace(@RequestBody SpaceUpdateRequest spaceUpdateRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(spaceUpdateRequest == null||spaceUpdateRequest.getId()<=0, ErrorCode.PARAMS_ERROR);
        Long id = spaceUpdateRequest.getId();
        Space oldSpace = spaceService.getById(id);
        if (oldSpace == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        Space space = new Space();
        BeanUtils.copyProperties(spaceUpdateRequest, space);
        spaceService.validSpace(space, false);
        spaceService.fillSpaceBySpaceLevel(space);
        boolean result = spaceService.updateById(space);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }
    @PostMapping("/edit")
    @ApiOperation(value = "编辑空间")
    public BaseResponse<Boolean> editSpace(@RequestBody SpaceUpdateRequest spaceUpdateRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(spaceUpdateRequest == null||spaceUpdateRequest.getId()<=0, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        Space oldSpace = spaceService.getById(spaceUpdateRequest.getId());
        if (oldSpace == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        if (!oldSpace.getUserId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        Space space = new Space();
        BeanUtils.copyProperties(spaceUpdateRequest, space);
        spaceService.validSpace(space, false);
        spaceService.fillSpaceBySpaceLevel(space);
        space.setEditTime(new Date());
        boolean result = spaceService.updateById(oldSpace);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }
    //getById
    @PostMapping("/get")
    @ApiOperation(value = "获取空间admin")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Space> getSpaceById(long id) {
        ThrowUtils.throwIf(id <=0, ErrorCode.PARAMS_ERROR);
        Space space = spaceService.getById(id);
        return ResultUtils.success(space);
    }
    //get/VO
    @GetMapping("/get/vo")
    @ApiOperation(value = "获取空间")
    public BaseResponse<SpaceVO> getSpaceVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Space space = spaceService.getById(id);
//        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
        SpaceVO spaceVO = spaceService.getSpaceVO(space, request);
        User loginUser = userService.getLoginUser(request);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        spaceVO.setPermissionList(permissionList);
        // 获取封装类
        return ResultUtils.success(spaceVO);
    }
    //list/page
    @PostMapping("/list/page")
    @ApiOperation(value = "获取空间列表")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Space>> listPicture(@RequestBody SpaceQueryRequest spaceQueryRequest){
        ThrowUtils.throwIf(spaceQueryRequest==null,ErrorCode.PARAMS_ERROR);
        Page<Space> spacePage = spaceService.page(new Page<>(spaceQueryRequest.getCurrent(), spaceQueryRequest.getPageSize()),
                spaceService.getQueryWrapper(spaceQueryRequest));
        return ResultUtils.success(spacePage);
    }
    //list/page/VO
    @PostMapping("/list/page/vo")
    @ApiOperation(value = "获取空间列表(封装类)")
    public BaseResponse<Page<SpaceVO>> listPictureVO(@RequestBody SpaceQueryRequest spaceQueryRequest){
        ThrowUtils.throwIf(spaceQueryRequest==null,ErrorCode.PARAMS_ERROR);
        Page<Space> spacePage = spaceService.page(new Page<>(spaceQueryRequest.getCurrent(), spaceQueryRequest.getPageSize()),
                spaceService.getQueryWrapper(spaceQueryRequest));
        Page<SpaceVO> spaceVOPage = spaceService.getSpaceVOPage(spacePage);
        return ResultUtils.success(spaceVOPage);
    }
    @GetMapping("/list/level")
    @ApiOperation(value = "获取空间等级")
    public BaseResponse<List<SpaceLevel>> getSpaceLevel(){
        List<SpaceLevel> spaceLevelList = Arrays.stream(SpaceLevelEnum.values())
                .map(spaceLevelEnum -> new SpaceLevel(
                        spaceLevelEnum.getValue(),
                        spaceLevelEnum.getText(),
                        spaceLevelEnum.getMaxCount(),
                        spaceLevelEnum.getMaxSize()
                ))
                .collect(Collectors.toList());
        return ResultUtils.success(spaceLevelList);
    }
}
